<template>
  <div class="loginContainer">
    <el-card header="后台管理系统登录">
      <el-form
        ref="ruleForm"
        :rules="rules"
        :model="formLogin"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="formLogin.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="formLogin.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">
            登录
          </el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { login } from '../api/users'
import { setToken } from '../utils/auth'
export default {
  data() {
    return {
      formLogin: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.formLogin)
            .then(({ data }) => {
              let res = data
              console.log(res)
              if (res.code === 1000) {
                setToken(data.data.token, data.data.refreshToken)
                localStorage.setItem('username', data.data.username)
                this.$router.push('/')
              } else {
                this.$message({ type: 'error', message: res.msg })
              }
            })
            .catch((err) => {
              this.$message({ type: 'error', message: err })
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
}
</script>
<style>
.loginContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #eeeeee;
}
.el-card__header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 25px;
  color: rgb(124, 231, 231);
}
.el-card__body {
  width: 400px;
}

.el-form-item__content {
  margin-left: 0px !important;
}
</style>
